"""Check if cloud ut is updated"""
from aligo import Aligo
from ut import UT
import csv


class FileTypeError(Exception):
    def __str__(self):
        return 'Error: File type is not the same'


# 无法解决文件重命名问题
class ContentError(Exception):
    def __str__(self):
        return 'Error: Content is not parallel'


# ut = updated_time
class CheckCloud:
    def __init__(self):
        # 获取 refresh_token 并进行登录
        with open('refresh_token', 'r') as refresh_token:
            self.ali_obj = Aligo(refresh_token=refresh_token.read())
        # 获取云端 ut 的文件 id
        self.cloud_ut_id = self._get_ut_id()
        self.cloud_ut = []
        self.local_ut = []
        self.file_ut_list = []

    # 检查ut是否存在，并读取内容
    def _get_local_ut(self):
        try:
            with open('D:\\SYNC\\updated_time.csv', 'r', newline='', encoding='utf-8') as file:
                for row in csv.reader(file):
                    self.local_ut.append(UT(row[0], row[1], row[2]))
        except Exception as error:
            if isinstance(error, FileNotFoundError):
                return False
        return True

    # 获取云端 ut 的文件 id
    def _get_ut_id(self):
        sync_id = None
        for each in self.ali_obj.get_file_list():
            if each.name == 'SYNC':
                sync_id = each.file_id
                break
        for each in self.ali_obj.get_file_list(sync_id):
            if each.name == 'updated_time.csv':
                return each.file_id
        return None

    # 下载并读取云端ut
    def _get_cloud_ut(self):
        file_path = self.ali_obj.download_file(self.cloud_ut_id)
        print(file_path)
        with open(file_path, 'r', newline='', encoding='utf-8') as file:
            for row in csv.reader(file):
                self.cloud_ut.append(UT(row[0], row[1], row[2]))

    # self.file_ut_list = [(file_name, flag)]
    # 若云端更新flag则为 True，反之则为 False
    def _compare_ut(self):
        try:
            for local_ut, cloud_ut in self.local_ut, self.cloud_ut:
                local_ut: UT
                cloud_ut: UT
                if local_ut.name == cloud_ut.name:
                    if local_ut.type == cloud_ut.type:
                        if local_ut.updated_time < cloud_ut.updated_time:
                            self.file_ut_list.append((cloud_ut.name, cloud_ut.updated_time))
                        else:
                            self.file_ut_list.append((local_ut.name, local_ut.updated_time))
                    else:
                        raise FileTypeError
                else:
                    raise ContentError
        except Exception as error:
            if isinstance(error, ContentError):
                print(ContentError)
                exit()
            else:
                print('Error: ', error)

    # 入口函数，返回文件更新情况列表
    def run(self) -> list:
        try:
            self._get_cloud_ut()
            self._compare_ut()
        except Exception as error:
            print('Error: ', error)
        finally:
            return self.file_ut_list
